{include file="common/pc/header" title="组织架构" /}

<style>
    #left {
        width: 200px;
        height: 100vh;
        border-right: solid 1px #ccc;
        overflow-y: scroll;
    }

    #left .layui-tree-skin-dept .layui-tree-branch {
        display: none;
    }

    #left .layui-tree-skin-dept .layui-tree-leaf {
        font-size: 10px;
        margin-left: 2px;
    }

    #depts .current-show-dept > a,
    #depts .current-show-dept > i,
    #depts .current-show-dept > a i {
        color: #5FB878;
    }

    #main {
        width: calc(100% - 210px);
    }

    #main .layui-card-header {
        background: #f2f2f2;
        border: solid 1px #eee;
        border-left: none;
        border-right: none;
    }

    #main .layui-card-body.user-list {
        padding-left: 0;
        padding-top: 0;
    }

    #main .dept-btn-group {
        margin-left: 10px;
    }

    #main .user-list ul li {
        padding-left: 40px;
        border-bottom: solid 1px #eee;
        height: 40px;
        line-height: 40px;
    }

    #main .dept-list .dept-item {
        margin-left: 10px;
    }

    #deptUsersFrame {
        width: 100%;
        border: none;
        min-height: calc(100vh - 150px);
    }

    #splitLine {
        float: left;
        height: 100vh;
        width: 3px;
        overflow: hidden;
        background: #f8f8f8;
        cursor: w-resize;
    }
</style>

<div class="layui-row" id="box">
    <div class="layui-col-xs6" id="left">
        <ul id="depts"></ul>
    </div>
    <div id="splitLine"></div>
    <div class="layui-col-xs6" id="main">
        <div class="layui-card">
            <div class="layui-card-header">
                <span class="dept-path"></span>
                <span class="layui-btn-group dept-btn-group">
                        <button class="layui-btn layui-btn-default layui-btn-xs edit-dept-btn">
                            <i class="layui-icon layui-icon-edit"></i><span></span>
                        </button>
                        <button class="layui-btn layui-btn-normal layui-btn-xs add-sub-dept-btn">
                            <i class="layui-icon layui-icon-add-1"></i><span></span>
                        </button>
                        <button class="layui-btn layui-btn-danger layui-btn-xs del-dept-btn">
                            <i class="layui-icon layui-icon-delete"></i><span></span>
                        </button>
                        {if condition="!empty($enterprise['corpid'])"}
                        <button class="layui-btn layui-btn-warm layui-btn-xs sync-ding-btn" title="从钉钉中同步通讯录">
                            <i class="layui-icon layui-icon-download-circle"></i><span>从钉钉中同步通讯录</span>
                        </button>
                        {/if}
                    </span>
            </div>
            <div class="layui-card-body">
                <div class="dept-info">
                    部门名称：<span class="dept-title"></span>
                </div>
                <div class="sub-depts">
                    下级部门：<span class="dept-list"></span>
                </div>
                <div class="dept-users">
                    <iframe id="deptUsersFrame" class="auto-height-iframe" data-delta-height="20"></iframe>
                </div>
            </div>
        </div>
    </div>
</div>

{php}
$enterpriseJson = json_encode($enterprise);
{/php}
<script>
    var deptTree = {$deptTree};
    var deptPath = {};
    var enterprise = {$enterpriseJson};
</script>

<script>
    /**
     * 部门节点点击
     */
    function onDeptTreeNodeClick(node, $elem) {
        $("#depts li").removeClass("current-show-dept")
        $elem.parents("li").first().addClass("current-show-dept");

        if (node.type == 'enterprise') {
            //企业根节点
            $("#main .edit-dept-btn span").html("修改企业信息");
            $("#main .add-sub-dept-btn span").html("添加下级部门");
            $("#main .sync-ding-btn").show();
            $("#main .del-dept-btn").hide();
        } else {
            //部门节点
            $("#main .edit-dept-btn span").html("修改部门信息");
            $("#main .add-sub-dept-btn span").html("添加下级部门");
            $("#main .del-dept-btn span").html("删除部门");
            $("#main .sync-ding-btn").hide();
            $("#main .del-dept-btn").show();
        }
        var subDepts = node.children;

        $("#main").data("node", node);
        $("#main .dept-title").html(node.name);
        $("#main .dept-path").html(deptPath[node.id].join(" - "));

        if (subDepts.length > 0) {
            $("#main .sub-depts").show();
        } else {
            $("#main .sub-depts").hide();
        }
        $("#main .dept-list").html("");
        $.each(subDepts, function () {
            var htm = '<span class="layui-badge layui-bg-blue dept-item">' + this.name + '</span>';
            $("#main .dept-list").append(htm);
        });

        $("#deptUsersFrame").attr("src", "/core/enterprise.org.user/all?eid={$eid}&deptid=" + node.id);
    }

    /**
     * 获取树配置
     */
    function getDeptTreeOption() {
        var option = {};
        option.elem = "#depts";
        option.skin = 'dept';
        option.click = function (node) {
            var $elem;
            if (typeof event != 'undefined') {
                $elem = $(event.target);
            } else {
                //Firefox下面，此处没有event对象
                $elem = $("#depts").data("current-dept-elem");
            }
            onDeptTreeNodeClick(node, $elem);
        };
        var node = {
            'id': 1,
            'name': enterprise.title,
            'data': enterprise,
            'type': 'enterprise',
            'spread': true,
            'children': []
        };

        $.each(deptTree, function () {
            var childNode = makeDeptTreeNode(this);
            node.children.push(childNode);
        });

        option.nodes = [node];
        return option;
    }

    /**
     * 生成部门节点
     *
     * @param dept
     * @returns {{name: *, data: *, type: string, children: Array}}
     */
    function makeDeptTreeNode(dept) {
        var node = {
            'id': dept.id,
            'name': dept.title,
            'data': dept,
            'type': 'dept',
            'children': []
        };

        if (dept.childs) {
            $.each(dept.childs, function () {
                node.children.push(makeDeptTreeNode(this));
            });
        }

        return node;
    }

    /**
     * 初始化部门路径
     *
     * @param currentDeptId
     * @param currentDeptPath
     * @param currentDeptTreeChildItems
     */
    function initDeptPath(currentDeptId, currentDeptPath, currentDeptTreeChildItems) {
        deptPath[currentDeptId] = currentDeptPath;
        if (!currentDeptTreeChildItems) {
            return;
        }
        $.each(currentDeptTreeChildItems, function () {
            initDeptPath(this.id, currentDeptPath.concat(this.title), this.childs);
        });
    }

    /**
     * 初始化事件
     */
    function initEvent() {
        //同步钉钉
        $("#main .sync-ding-btn").click(function () {
            layer.confirm("确认从钉钉同步通讯录？", function (index, layero) {
                g.loading();
                syncDing(function () {
                    g.loading(false);
                });
            });
        });
        //编辑部门信息
        $("#main .edit-dept-btn").click(function () {
            var node = $("#main").data("node");
            if (node.type == 'enterprise') {
                //编辑企业信息
                openDialog("编辑企业信息", '/core/enterprise.info/config?eid={$eid}');
            } else {
                //编辑部门信息
                openDialog("编辑部门信息", '/core/enterprise.org.dept/edit?eid={$eid}&deptid=' + node.id);
            }
        });
        //删除部门
        $("#main .del-dept-btn").click(function () {
            var node = $("#main").data("node");
            layer.confirm("确认删除部门" + node.name + "及其所有子部门?", function () {
                layer.prompt({
                    formType: 0,
                    value: '',
                    title: '请输入部门名称【' + node.name + '】再次确认'
                }, function (value, index, elem) {
                    if (value != node.name) {
                        layer.alert("输入错误");
                        return;
                    }
                    g.loading();
                    $.post("/core/enterprise.org.dept/del?eid={$eid}", {
                        "deptid": node.id
                    }, function (ret) {
                        g.loading(false);
                        if (ret.code == 1) {
                            layer.msg(ret.msg);
                            document.location.reload();
                        } else {
                            layer.alert(ret.msg);
                        }
                    }, "json");
                });
            });
        });
        //添加子部门
        $("#main .add-sub-dept-btn").click(function () {
            var node = $("#main").data("node");
            layer.prompt({
                formType: 0,
                value: '',
                title: '您正在向【' + node.name + '】下添加子部门，请输入子部门名称'
            }, function (value, index, elem) {
                g.loading();
                $.post("/core/enterprise.org.dept/add?eid={$eid}", {
                    "parentId": node.id,
                    "title": value
                }, function (ret) {
                    g.loading(false);
                    if (ret.code == 1) {
                        layer.msg(ret.msg);
                        document.location.reload();
                    } else {
                        layer.alert(ret.msg);
                    }
                }, "json");
            });
        });

        $("#depts li a").mouseover(function (event) {
            $("#depts").data("current-dept-elem", $(event.target));
        });
    }

    /**
     * 打开弹窗
     */
    function openDialog(title, url) {
        layer.open({
            type: 2,
            title: title,
            shadeClose: true,
            shade: 0.8,
            maxmin: false,
            resize: true,
            area: ['80vw', '80vh'],
            content: url,
            cancel: function () {
            }
        });
    }

    /**
     * 同步钉钉通讯录
     *
     * @param callback
     */
    function syncDing(callback) {
        $.post("/core/enterprise.org.index/syncDing?eid={$eid}", {_: new Date().getTime()}, function (ret) {
            if (ret.code == 1) {
                layer.msg(ret.msg);
                document.location.reload();
            } else {
                layer.alert(ret.msg);
            }
            callback && callback();
        }, "json");
    }

    layui.use(['tree', 'table'], function () {
        //初始化部门路径
        initDeptPath("1", [enterprise.title], deptTree);

        //初始化左侧部门菜单
        var option = getDeptTreeOption();
        layui.tree(option);
        onDeptTreeNodeClick(option.nodes[0], $("#depts li a").first());

        //初始化事件
        initEvent();
        initDargSize();
    });

    function initDargSize() {
        $(document).ready(function () {
            var oBox = document.getElementById("box"),
                oLeft = document.getElementById("left"),
                oRight = document.getElementById("main"),
                oLine = document.getElementById("splitLine");
            oLine.onmousedown = function (e) {
                var disX = (e || event).clientX;
                oLine.left = oLine.offsetLeft;
                document.onmousemove = function (e) {
                    var iT = oLine.left + ((e || event).clientX - disX);
                    var e = e || window.event, tarnameb = e.target || e.srcElement;
                    var maxT = oBox.clientWight - oLine.offsetWidth;
                    oLine.style.margin = 0;
                    iT < 0 && (iT = 0);
                    iT > maxT && (iT = maxT);
                    oLine.style.left = oLeft.style.width = iT + "px";
                    oRight.style.width = (oBox.clientWidth - iT - 10) + "px";
                    return false
                };
                document.onmouseup = function () {
                    document.onmousemove = null;
                    document.onmouseup = null;
                    oLine.releaseCapture && oLine.releaseCapture()
                };
                oLine.setCapture && oLine.setCapture();
                return false
            };
        });
    }
</script>

{include file="common/pc/footer"/}